<!doctype html>

<html>
<head>
  <link rel="shortcut icon" href="static/images/favicon.ico" type="image/x-icon">
  <title>xhr.js (Closure Library API Documentation - JavaScript)</title>
  <link rel="stylesheet" href="static/css/base.css">
  <link rel="stylesheet" href="static/css/doc.css">
  <link rel="stylesheet" href="static/css/sidetree.css">
  <link rel="stylesheet" href="static/css/prettify.css">

  <script>
     var _staticFilePath = "static/";
     var _typeTreeName = "goog";
     var _fileTreeName = "Source";
  </script>

  <script src="static/js/doc.js">
  </script>


  <meta charset="utf8">
</head>

<body onload="grokdoc.onLoad();">

<div id="header">
  <div class="g-section g-tpl-50-50 g-split">
    <div class="g-unit g-first">
      <a id="logo" href="index.html">Closure Library API Documentation</a>
    </div>

    <div class="g-unit">
      <div class="g-c">
        <strong>Go to class or file:</strong>
        <input type="text" id="ac">
      </div>
    </div>
  </div>
</div>

<div class="clear"></div>

<h2><a href="local_closure_goog_labs_net_xhr.js.html">xhr.js</a></h2>

<pre class="prettyprint lang-js">
<a name="line1"></a>// Copyright 2011 The Closure Library Authors. All Rights Reserved.
<a name="line2"></a>//
<a name="line3"></a>// Licensed under the Apache License, Version 2.0 (the &quot;License&quot;);
<a name="line4"></a>// you may not use this file except in compliance with the License.
<a name="line5"></a>// You may obtain a copy of the License at
<a name="line6"></a>//
<a name="line7"></a>//      http://www.apache.org/licenses/LICENSE-2.0
<a name="line8"></a>//
<a name="line9"></a>// Unless required by applicable law or agreed to in writing, software
<a name="line10"></a>// distributed under the License is distributed on an &quot;AS-IS&quot; BASIS,
<a name="line11"></a>// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<a name="line12"></a>// See the License for the specific language governing permissions and
<a name="line13"></a>// limitations under the License.
<a name="line14"></a>
<a name="line15"></a>
<a name="line16"></a>/**
<a name="line17"></a> * @fileoverview Offered as an alternative to XhrIo as a way for making requests
<a name="line18"></a> * via XMLHttpRequest.  Instead of mirroring the XHR interface and exposing
<a name="line19"></a> * events, results are used as a way to pass a &quot;promise&quot; of the response to
<a name="line20"></a> * interested parties.
<a name="line21"></a> *
<a name="line22"></a> */
<a name="line23"></a>
<a name="line24"></a>goog.provide(&#39;goog.labs.net.xhr&#39;);
<a name="line25"></a>goog.provide(&#39;goog.labs.net.xhr.Error&#39;);
<a name="line26"></a>goog.provide(&#39;goog.labs.net.xhr.HttpError&#39;);
<a name="line27"></a>goog.provide(&#39;goog.labs.net.xhr.Options&#39;);
<a name="line28"></a>goog.provide(&#39;goog.labs.net.xhr.PostData&#39;);
<a name="line29"></a>goog.provide(&#39;goog.labs.net.xhr.TimeoutError&#39;);
<a name="line30"></a>
<a name="line31"></a>goog.require(&#39;goog.Promise&#39;);
<a name="line32"></a>goog.require(&#39;goog.debug.Error&#39;);
<a name="line33"></a>goog.require(&#39;goog.json&#39;);
<a name="line34"></a>goog.require(&#39;goog.net.HttpStatus&#39;);
<a name="line35"></a>goog.require(&#39;goog.net.XmlHttp&#39;);
<a name="line36"></a>goog.require(&#39;goog.string&#39;);
<a name="line37"></a>goog.require(&#39;goog.uri.utils&#39;);
<a name="line38"></a>
<a name="line39"></a>
<a name="line40"></a>
<a name="line41"></a>goog.scope(function() {
<a name="line42"></a>var _ = goog.labs.net.xhr;
<a name="line43"></a>var HttpStatus = goog.net.HttpStatus;
<a name="line44"></a>
<a name="line45"></a>
<a name="line46"></a>/**
<a name="line47"></a> * Configuration options for an XMLHttpRequest.
<a name="line48"></a> * - headers: map of header key/value pairs.
<a name="line49"></a> * - timeoutMs: number of milliseconds after which the request will be timed
<a name="line50"></a> *      out by the client. Default is to allow the browser to handle timeouts.
<a name="line51"></a> * - withCredentials: whether user credentials are to be included in a
<a name="line52"></a> *      cross-origin request.  See:
<a name="line53"></a> *      http://dev.w3.org/2006/webapi/XMLHttpRequest-2/#the-withcredentials-attribute
<a name="line54"></a> * - mimeType: allows the caller to override the content-type and charset for
<a name="line55"></a> *      the request, which is useful when requesting binary data.  See:
<a name="line56"></a> *      http://dev.w3.org/2006/webapi/XMLHttpRequest-2/#dom-xmlhttprequest-overridemimetype
<a name="line57"></a> * - xssiPrefix: Prefix used for protecting against XSSI attacks, which should
<a name="line58"></a> *      be removed before parsing the response as JSON.
<a name="line59"></a> *
<a name="line60"></a> * @typedef {{
<a name="line61"></a> *   headers: (Object.&lt;string&gt;|undefined),
<a name="line62"></a> *   timeoutMs: (number|undefined),
<a name="line63"></a> *   withCredentials: (boolean|undefined),
<a name="line64"></a> *   mimeType: (string|undefined),
<a name="line65"></a> *   xssiPrefix: (string|undefined)
<a name="line66"></a> * }}
<a name="line67"></a> */
<a name="line68"></a>_.Options;
<a name="line69"></a>
<a name="line70"></a>
<a name="line71"></a>/**
<a name="line72"></a> * Defines the types that are allowed as post data.
<a name="line73"></a> * @typedef {(ArrayBuffer|Blob|Document|FormData|null|string|undefined)}
<a name="line74"></a> */
<a name="line75"></a>_.PostData;
<a name="line76"></a>
<a name="line77"></a>
<a name="line78"></a>/**
<a name="line79"></a> * The Content-Type HTTP header name.
<a name="line80"></a> * @type {string}
<a name="line81"></a> */
<a name="line82"></a>_.CONTENT_TYPE_HEADER = &#39;Content-Type&#39;;
<a name="line83"></a>
<a name="line84"></a>
<a name="line85"></a>/**
<a name="line86"></a> * The Content-Type HTTP header value for a url-encoded form.
<a name="line87"></a> * @type {string}
<a name="line88"></a> */
<a name="line89"></a>_.FORM_CONTENT_TYPE = &#39;application/x-www-form-urlencoded;charset=utf-8&#39;;
<a name="line90"></a>
<a name="line91"></a>
<a name="line92"></a>/**
<a name="line93"></a> * Sends a get request, returning a promise that will be resolved
<a name="line94"></a> * with the response text once the request completes.
<a name="line95"></a> *
<a name="line96"></a> * @param {string} url The URL to request.
<a name="line97"></a> * @param {_.Options=} opt_options Configuration options for the request.
<a name="line98"></a> * @return {!goog.Promise.&lt;string&gt;} A promise that will be resolved with the
<a name="line99"></a> *     response text once the request completes.
<a name="line100"></a> */
<a name="line101"></a>_.get = function(url, opt_options) {
<a name="line102"></a>  return _.send(&#39;GET&#39;, url, null, opt_options).then(function(xhr) {
<a name="line103"></a>    return xhr.responseText;
<a name="line104"></a>  });
<a name="line105"></a>};
<a name="line106"></a>
<a name="line107"></a>
<a name="line108"></a>/**
<a name="line109"></a> * Sends a post request, returning a promise that will be resolved
<a name="line110"></a> * with the response text once the request completes.
<a name="line111"></a> *
<a name="line112"></a> * @param {string} url The URL to request.
<a name="line113"></a> * @param {_.PostData} data The body of the post request.
<a name="line114"></a> * @param {_.Options=} opt_options Configuration options for the request.
<a name="line115"></a> * @return {!goog.Promise.&lt;string&gt;} A promise that will be resolved with the
<a name="line116"></a> *     response text once the request completes.
<a name="line117"></a> */
<a name="line118"></a>_.post = function(url, data, opt_options) {
<a name="line119"></a>  return _.send(&#39;POST&#39;, url, data, opt_options).then(function(xhr) {
<a name="line120"></a>    return xhr.responseText;
<a name="line121"></a>  });
<a name="line122"></a>};
<a name="line123"></a>
<a name="line124"></a>
<a name="line125"></a>/**
<a name="line126"></a> * Sends a get request, returning a promise that will be resolved with
<a name="line127"></a> * the parsed response text once the request completes.
<a name="line128"></a> *
<a name="line129"></a> * @param {string} url The URL to request.
<a name="line130"></a> * @param {_.Options=} opt_options Configuration options for the request.
<a name="line131"></a> * @return {!goog.Promise.&lt;Object&gt;} A promise that will be resolved with the
<a name="line132"></a> *     response JSON once the request completes.
<a name="line133"></a> */
<a name="line134"></a>_.getJson = function(url, opt_options) {
<a name="line135"></a>  return _.send(&#39;GET&#39;, url, null, opt_options).then(function(xhr) {
<a name="line136"></a>    return _.parseJson_(xhr.responseText, opt_options);
<a name="line137"></a>  });
<a name="line138"></a>};
<a name="line139"></a>
<a name="line140"></a>
<a name="line141"></a>/**
<a name="line142"></a> * Sends a post request, returning a promise that will be resolved with
<a name="line143"></a> * the parsed response text once the request completes.
<a name="line144"></a> *
<a name="line145"></a> * @param {string} url The URL to request.
<a name="line146"></a> * @param {_.PostData} data The body of the post request.
<a name="line147"></a> * @param {_.Options=} opt_options Configuration options for the request.
<a name="line148"></a> * @return {!goog.Promise.&lt;Object&gt;} A promise that will be resolved with the
<a name="line149"></a> *     response JSON once the request completes.
<a name="line150"></a> */
<a name="line151"></a>_.postJson = function(url, data, opt_options) {
<a name="line152"></a>  return _.send(&#39;POST&#39;, url, data, opt_options).then(function(xhr) {
<a name="line153"></a>    return _.parseJson_(xhr.responseText, opt_options);
<a name="line154"></a>  });
<a name="line155"></a>};
<a name="line156"></a>
<a name="line157"></a>
<a name="line158"></a>/**
<a name="line159"></a> * Sends a request, returning a promise that will be resolved
<a name="line160"></a> * with the XHR object once the request completes.
<a name="line161"></a> *
<a name="line162"></a> * @param {string} method The HTTP method for the request.
<a name="line163"></a> * @param {string} url The URL to request.
<a name="line164"></a> * @param {_.PostData} data The body of the post request.
<a name="line165"></a> * @param {_.Options=} opt_options Configuration options for the request.
<a name="line166"></a> * @return {!goog.Promise.&lt;!goog.net.XhrLike.OrNative&gt;} A promise that will be
<a name="line167"></a> *     resolved with the XHR object once the request completes.
<a name="line168"></a> */
<a name="line169"></a>_.send = function(method, url, data, opt_options) {
<a name="line170"></a>  return new goog.Promise(function(resolve, reject) {
<a name="line171"></a>    var options = opt_options || {};
<a name="line172"></a>    var timer;
<a name="line173"></a>
<a name="line174"></a>    var xhr = goog.net.XmlHttp();
<a name="line175"></a>    try {
<a name="line176"></a>      xhr.open(method, url, true);
<a name="line177"></a>    } catch (e) {
<a name="line178"></a>      // XMLHttpRequest.open may throw when &#39;open&#39; is called, for example, IE7
<a name="line179"></a>      // throws &quot;Access Denied&quot; for cross-origin requests.
<a name="line180"></a>      reject(new _.Error(&#39;Error opening XHR: &#39; + e.message, url, xhr));
<a name="line181"></a>    }
<a name="line182"></a>
<a name="line183"></a>    // So sad that IE doesn&#39;t support onload and onerror.
<a name="line184"></a>    xhr.onreadystatechange = function() {
<a name="line185"></a>      if (xhr.readyState == goog.net.XmlHttp.ReadyState.COMPLETE) {
<a name="line186"></a>        window.clearTimeout(timer);
<a name="line187"></a>        // Note: When developing locally, XHRs to file:// schemes return
<a name="line188"></a>        // a status code of 0. We mark that case as a success too.
<a name="line189"></a>        if (HttpStatus.isSuccess(xhr.status) ||
<a name="line190"></a>            xhr.status === 0 &amp;&amp; !_.isEffectiveSchemeHttp_(url)) {
<a name="line191"></a>          resolve(xhr);
<a name="line192"></a>        } else {
<a name="line193"></a>          reject(new _.HttpError(xhr.status, url, xhr));
<a name="line194"></a>        }
<a name="line195"></a>      }
<a name="line196"></a>    };
<a name="line197"></a>    xhr.onerror = function() {
<a name="line198"></a>      reject(new _.Error(&#39;Network error&#39;, url, xhr));
<a name="line199"></a>    };
<a name="line200"></a>
<a name="line201"></a>    // Set the headers.
<a name="line202"></a>    var contentTypeIsSet = false;
<a name="line203"></a>    if (options.headers) {
<a name="line204"></a>      for (var key in options.headers) {
<a name="line205"></a>        xhr.setRequestHeader(key, options.headers[key]);
<a name="line206"></a>      }
<a name="line207"></a>      contentTypeIsSet = _.CONTENT_TYPE_HEADER in options.headers;
<a name="line208"></a>    }
<a name="line209"></a>
<a name="line210"></a>    // If a content type hasn&#39;t been set, default to form-urlencoded/UTF8 for
<a name="line211"></a>    // POSTs.  This is because some proxies have been known to reject posts
<a name="line212"></a>    // without a content-type.
<a name="line213"></a>    if (method == &#39;POST&#39; &amp;&amp; !contentTypeIsSet) {
<a name="line214"></a>      xhr.setRequestHeader(_.CONTENT_TYPE_HEADER, _.FORM_CONTENT_TYPE);
<a name="line215"></a>    }
<a name="line216"></a>
<a name="line217"></a>    // Set whether to pass cookies on cross-domain requests (if applicable).
<a name="line218"></a>    // @see http://dev.w3.org/2006/webapi/XMLHttpRequest-2/#the-withcredentials-attribute
<a name="line219"></a>    if (options.withCredentials) {
<a name="line220"></a>      xhr.withCredentials = options.withCredentials;
<a name="line221"></a>    }
<a name="line222"></a>
<a name="line223"></a>    // Allow the request to override the mime type, useful for getting binary
<a name="line224"></a>    // data from the server.  e.g. &#39;text/plain; charset=x-user-defined&#39;.
<a name="line225"></a>    // @see http://dev.w3.org/2006/webapi/XMLHttpRequest-2/#dom-xmlhttprequest-overridemimetype
<a name="line226"></a>    if (options.mimeType) {
<a name="line227"></a>      xhr.overrideMimeType(options.mimeType);
<a name="line228"></a>    }
<a name="line229"></a>
<a name="line230"></a>    // Handle timeouts, if requested.
<a name="line231"></a>    if (options.timeoutMs &gt; 0) {
<a name="line232"></a>      timer = window.setTimeout(function() {
<a name="line233"></a>        // Clear event listener before aborting so the errback will not be
<a name="line234"></a>        // called twice.
<a name="line235"></a>        xhr.onreadystatechange = goog.nullFunction;
<a name="line236"></a>        xhr.abort();
<a name="line237"></a>        reject(new _.TimeoutError(url, xhr));
<a name="line238"></a>      }, options.timeoutMs);
<a name="line239"></a>    }
<a name="line240"></a>
<a name="line241"></a>    // Trigger the send.
<a name="line242"></a>    try {
<a name="line243"></a>      xhr.send(data);
<a name="line244"></a>    } catch (e) {
<a name="line245"></a>      // XMLHttpRequest.send is known to throw on some versions of FF,
<a name="line246"></a>      // for example if a cross-origin request is disallowed.
<a name="line247"></a>      xhr.onreadystatechange = goog.nullFunction;
<a name="line248"></a>      window.clearTimeout(timer);
<a name="line249"></a>      reject(new _.Error(&#39;Error sending XHR: &#39; + e.message, url, xhr));
<a name="line250"></a>    }
<a name="line251"></a>  });
<a name="line252"></a>};
<a name="line253"></a>
<a name="line254"></a>
<a name="line255"></a>/**
<a name="line256"></a> * @param {string} url The URL to test.
<a name="line257"></a> * @return {boolean} Whether the effective scheme is HTTP or HTTPs.
<a name="line258"></a> * @private
<a name="line259"></a> */
<a name="line260"></a>_.isEffectiveSchemeHttp_ = function(url) {
<a name="line261"></a>  var scheme = goog.uri.utils.getEffectiveScheme(url);
<a name="line262"></a>  // NOTE(user): Empty-string is for the case under FF3.5 when the location
<a name="line263"></a>  // is not defined inside a web worker.
<a name="line264"></a>  return scheme == &#39;http&#39; || scheme == &#39;https&#39; || scheme == &#39;&#39;;
<a name="line265"></a>};
<a name="line266"></a>
<a name="line267"></a>
<a name="line268"></a>/**
<a name="line269"></a> * JSON-parses the given response text, returning an Object.
<a name="line270"></a> *
<a name="line271"></a> * @param {string} responseText Response text.
<a name="line272"></a> * @param {_.Options|undefined} options The options object.
<a name="line273"></a> * @return {Object} The JSON-parsed value of the original responseText.
<a name="line274"></a> * @private
<a name="line275"></a> */
<a name="line276"></a>_.parseJson_ = function(responseText, options) {
<a name="line277"></a>  var prefixStrippedResult = responseText;
<a name="line278"></a>  if (options &amp;&amp; options.xssiPrefix) {
<a name="line279"></a>    prefixStrippedResult = _.stripXssiPrefix_(
<a name="line280"></a>        options.xssiPrefix, prefixStrippedResult);
<a name="line281"></a>  }
<a name="line282"></a>  return goog.json.parse(prefixStrippedResult);
<a name="line283"></a>};
<a name="line284"></a>
<a name="line285"></a>
<a name="line286"></a>/**
<a name="line287"></a> * Strips the XSSI prefix from the input string.
<a name="line288"></a> *
<a name="line289"></a> * @param {string} prefix The XSSI prefix.
<a name="line290"></a> * @param {string} string The string to strip the prefix from.
<a name="line291"></a> * @return {string} The input string without the prefix.
<a name="line292"></a> * @private
<a name="line293"></a> */
<a name="line294"></a>_.stripXssiPrefix_ = function(prefix, string) {
<a name="line295"></a>  if (goog.string.startsWith(string, prefix)) {
<a name="line296"></a>    string = string.substring(prefix.length);
<a name="line297"></a>  }
<a name="line298"></a>  return string;
<a name="line299"></a>};
<a name="line300"></a>
<a name="line301"></a>
<a name="line302"></a>
<a name="line303"></a>/**
<a name="line304"></a> * Generic error that may occur during a request.
<a name="line305"></a> *
<a name="line306"></a> * @param {string} message The error message.
<a name="line307"></a> * @param {string} url The URL that was being requested.
<a name="line308"></a> * @param {!goog.net.XhrLike.OrNative} xhr The XHR that failed.
<a name="line309"></a> * @extends {goog.debug.Error}
<a name="line310"></a> * @constructor
<a name="line311"></a> */
<a name="line312"></a>_.Error = function(message, url, xhr) {
<a name="line313"></a>  _.Error.base(this, &#39;constructor&#39;, message + &#39;, url=&#39; + url);
<a name="line314"></a>
<a name="line315"></a>  /**
<a name="line316"></a>   * The URL that was requested.
<a name="line317"></a>   * @type {string}
<a name="line318"></a>   */
<a name="line319"></a>  this.url = url;
<a name="line320"></a>
<a name="line321"></a>  /**
<a name="line322"></a>   * The XMLHttpRequest corresponding with the failed request.
<a name="line323"></a>   * @type {!goog.net.XhrLike.OrNative}
<a name="line324"></a>   */
<a name="line325"></a>  this.xhr = xhr;
<a name="line326"></a>};
<a name="line327"></a>goog.inherits(_.Error, goog.debug.Error);
<a name="line328"></a>
<a name="line329"></a>
<a name="line330"></a>/** @override */
<a name="line331"></a>_.Error.prototype.name = &#39;XhrError&#39;;
<a name="line332"></a>
<a name="line333"></a>
<a name="line334"></a>
<a name="line335"></a>/**
<a name="line336"></a> * Class for HTTP errors.
<a name="line337"></a> *
<a name="line338"></a> * @param {number} status The HTTP status code of the response.
<a name="line339"></a> * @param {string} url The URL that was being requested.
<a name="line340"></a> * @param {!goog.net.XhrLike.OrNative} xhr The XHR that failed.
<a name="line341"></a> * @extends {_.Error}
<a name="line342"></a> * @constructor
<a name="line343"></a> * @final
<a name="line344"></a> */
<a name="line345"></a>_.HttpError = function(status, url, xhr) {
<a name="line346"></a>  _.HttpError.base(
<a name="line347"></a>      this, &#39;constructor&#39;, &#39;Request Failed, status=&#39; + status, url, xhr);
<a name="line348"></a>
<a name="line349"></a>  /**
<a name="line350"></a>   * The HTTP status code for the error.
<a name="line351"></a>   * @type {number}
<a name="line352"></a>   */
<a name="line353"></a>  this.status = status;
<a name="line354"></a>};
<a name="line355"></a>goog.inherits(_.HttpError, _.Error);
<a name="line356"></a>
<a name="line357"></a>
<a name="line358"></a>/** @override */
<a name="line359"></a>_.HttpError.prototype.name = &#39;XhrHttpError&#39;;
<a name="line360"></a>
<a name="line361"></a>
<a name="line362"></a>
<a name="line363"></a>/**
<a name="line364"></a> * Class for Timeout errors.
<a name="line365"></a> *
<a name="line366"></a> * @param {string} url The URL that timed out.
<a name="line367"></a> * @param {!goog.net.XhrLike.OrNative} xhr The XHR that failed.
<a name="line368"></a> * @extends {_.Error}
<a name="line369"></a> * @constructor
<a name="line370"></a> * @final
<a name="line371"></a> */
<a name="line372"></a>_.TimeoutError = function(url, xhr) {
<a name="line373"></a>  _.TimeoutError.base(this, &#39;constructor&#39;, &#39;Request timed out&#39;, url, xhr);
<a name="line374"></a>};
<a name="line375"></a>goog.inherits(_.TimeoutError, _.Error);
<a name="line376"></a>
<a name="line377"></a>
<a name="line378"></a>/** @override */
<a name="line379"></a>_.TimeoutError.prototype.name = &#39;XhrTimeoutError&#39;;
<a name="line380"></a>
<a name="line381"></a>});  // goog.scope
</pre>


</body>
</html>
